import React from "react";
import { connect } from "dva";
import { Button, Radio, Form, Input, message, Progress } from "antd";
import "./Article-mon.less";
import "dashjs";
import Ueditor from "./Ueditor-mon";
import { uploadImgBase64 } from "../../services/fetch";
// import { noImg } from "../../utils/request";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

@connect(({ add }) => ({
  add: add
}))
class Article extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      editorHtml: "",
      editorText: "",
      radioValue: 1,
      marginLeft: 0,
      marginRight: 0,
      titleLength: 0,
      keyLength: 0,
      introLength: 0,
      progress: 0
    };
    this.props.onRef(this);
  }

  componentDidMount() {
    // window.PubSub.subscribe('editor', this.setEditor)
    window.PubSub.subscribe("pushDataToContent", this.pushDataToContent);
  }

  pushDataToContent = item => {
    this.props.form.setFieldsValue(item);
  };
  //从内容库选择到编辑器
  setUeditor = () => {
    let ue = window.UE.getEditor("content");
    ue.focus();
    this.props.dispatch({ type: "add/saveMchType", data: "editor" });
  };
  showVideoModal = e => {
    // console.log(e)
  };
  //订阅
  setEditor = data => {
    let ue = window.UE.getEditor("content");
    //设置文本值
    let datas = "";

    //如果当前标题为空，那么则使用内容库的素材标题
    let formData = this.props.form.getFieldsValue();
    if (!formData.information_title) {
      this.props.form.setFieldsValue({
        information_title: data.name
      });
    }
    // console.log(data);

    switch (data.type) {
      case "biz_sobey_picture":
        if (data.streamingUrl == "") {
          message.error("当前素材不可用");
          return;
        }
        datas = `<img src="${data.streamingUrl}" alt='...'/>`;
        break;
      case "biz_sobey_video":
        if (data.streamingUrl == "") {
          message.error("当前素材不可用");
          return;
        }
        datas = `<p style="text-align:center"><video data-dashjs-player id="${data.contentId}" src="${data.streamingUrl}" poster="${data.keyFrameUrl}"
                controls webkit-playsinline="true" x-webkit-airplay="true" 
                playsinline="true" x5-playsinline="true"></video></p><h3 style="display: none"><br /> ${data.name}</h3>`;
        break;
      case "biz_sobey_audio":
        if (data.streamingUrl == "") {
          message.error("当前素材不可用");
          return;
        }
        datas = `<p><audio src=${data.streamingUrl} style="margin: 10px auto;display: block;" controls>您的浏览器不支持 audio 标签。</audio></p>`;
        break;
      case "biz_sobey_hypermedia":
        datas = data.note = data.note.replace(/[\\]/g, "");
        break;
      default:
        break;
    }
    ue.ready(function() {
      ue.execCommand("insertHtml", datas);
      // ue.setContent('<p>　</p>', true);
      // window.dashjs.MediaPlayerFactory.createAll();
      // window.player = window.dashjs.MediaPlayer().create();
      // window.player.initialize(document.querySelector("#"+data.contentId), data.streamingUrl, true);
    });
  };
  onChangeRadio = e => {
    this.setState({
      radioValue: e.target.value
    });
    if (e.target.value == 1) {
      this.setFields({
        url: ""
      });
    }
  };
  /**
   * 关闭
   */
  close = key => {
    this.props.dispatch({
      type: "add/close",
      key: key
    });
  };
  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue();
    let about = [];
    this.props.add.gltjData.map((item, index) => {
      about.push(item.information_id);
    });
    data["about"] = about.join();
    data["type"] = 1;
    let ue = window.UE.getEditor("content");
    data.content = ue.getContent();

    return data;
  };

  /**
   * 获取表单值
   */
  getFieldsValue = () => {
    let data = this.props.form.getFieldsValue();

    this.props.form.validateFields();
    let validateArr = this.props.form.getFieldsError();
    let isDown = true;
    for (const key in validateArr) {
      if (validateArr.hasOwnProperty(key)) {
        //判断是否有效验错误
        if (validateArr[key]) {
          isDown = false;
          return;
        }
      }
    }
    if (isDown) {
      let about = [];
      this.props.add.gltjData.map((item, index) => {
        about.push(item.information_id);
      });
      data["about"] = about.join();
      data["type"] = 1;
      let ue = window.UE.getEditor("content");
      data.content = ue.getContent();

      return data;
    }
  };
  /**
   * 重置表单
   */
  resetFields = () => {
    this.props.form.resetFields();
    let ue = window.UE.getEditor("content");
    ue.execCommand("cleardoc");
  };
  /**
   * 设置值
   */
  setFields = data => {
    // let formData = this.props.form.getFieldsValue();
    // if (formData.information_title) {
    //     data.information_title = formData.information_title;
    // }
    let setData = {};
    setData.information_title = data.title;
    setData.intro = data.summary;
    setData.key_word = data.keyword;
    setData.content = data.content;
    setData.url = data.url;
    this.props.form.setFieldsValue(setData);
    setTimeout(() => {
      if (window.UE) {
        let ue = window.UE.getEditor("content");
        ue.ready(function() {
          if (setData.content) {
            ue.setContent(setData.content);
          }
        });
      }
    }, 1000);
    //如果是URL链接
    if (data.url) {
      this.setState({
        radioValue: 2
      });
    } else {
      this.setState({
        radioValue: 1
      });
    }

    //只有在使用已发布视频或资讯时才会执行此处
    if (data.mType) {
      if (data.mType == "video") {
        if (data.video_type == 1) {
          let ue = window.UE.getEditor("content");
          ue.focus();
          let datas = `<p></p><p></p><video src="${data.video_src}"  poster="${data.thumbnail}"
                                controls
                                webkit-playsinline="true"
                                x-webkit-airplay="true"
                                playsinline="true"
                                x5-playsinline="true"
                               >
                                您的浏览器不支持 video 标签。
                                </video><p></p>`;
          ue.execCommand("insertHtml", datas);
        } else if (data.video_type == 2) {
          this.createAudioToUeditor(data.video_src);
        }
      } else if (data.mType == "information") {
        let ue = window.UE.getEditor("content");
        ue.focus();
        ue.execCommand("insertHtml", data.content);
      }
    }
    //此处操作编辑器内容移动到编辑器组件内部操作
    // if (data.content) {
    //     window.onload = function () {
    //         let ue = window.UE.getEditor('content');
    //         ue.ready(function () {
    //             ue.setContent(data.content);
    //         });
    //     }
    //     // setTimeout(() => { //有时UE 还没加载完成，后端数据就返回了，会报错
    //     //     let ue = window.UE.getEditor('content');
    //     //     ue.ready(function () {
    //     //         ue.setContent(data.content);
    //     //     });
    //     // }, 1000)

    // }
    if (data.about) {
      this.props.dispatch({ type: "add/setPushClick", data: data.about_list });
    }
  };
  /**
   * 获取title length
   */
  getTitleLength = e => {
    let length = e.target.value.length;
    if (length <= 60) {
      this.setState({
        titleLength: length
      });
    }
    window.PubSub.publish("tabTitle", e.target.value);
  };

  /**
   * 创建音频到富文本中
   */
  createAudioToUeditor = url => {
    let ue = window.UE.getEditor("content");
    ue.focus();
    let datas = `<p></p><audio style="margin: 10px auto;display: block;" src="${url}" controls>您的浏览器不支持 audio 标签。</audio><p></p>`;
    ue.execCommand("insertHtml", datas);
  };

  /**
   * 创建图片到富文本中
   */
  createImgToUeditor = url => {
    let ue = window.UE.getEditor("content");
    ue.focus();
    let datas = `<p></p><img style="margin: 10px auto;display: block;" src="${url}" /><p></p>`;
    ue.execCommand("insertHtml", datas);
  };

  /**
   * 创建视频到富文本中
   */
  createVideoToUeditor = url => {
    /**
     * 上传视频自动生成封面图功能  详解
     * 调用上传视频接口后端返回上传成功mp4地址，先放到一个隐藏的video标签中，然后利用canvas的drawImage方法截取视频关键帧，获得图片的base64地址
     * 然后在调用后端接口将base64地址上传后转换成.jpg的资源文件地址，最后在设置到video标签的poster属性上，完成视频上传自动生成封面图功能
     *
     * 彩蛋，crossorigin="anonymous" 加了这个属性后可解决canvas获取跨域资源问题
     * 但是需要后端配合修改Access-Control-Allow-Origin
     * 由于本地老是报错出现跨域问题，至今没解决。所以每次只有佛系修改代码。打包后传到服务器上测试。
     *
     * */
    let canvas = document.createElement("canvas");
    let hidden_video = document.getElementById("hidden_video");
    let data;
    var timeStamp = +new Date();
    hidden_video.setAttribute("src", url + "?" + timeStamp);
    const hide = message.loading("视频上传成功,封面图生成中...", 0);

    hidden_video.oncanplay = () => {
      var videoWidth = hidden_video.videoWidth > 0 ? hidden_video.videoWidth : 295;
      var videoHeight = hidden_video.videoHeight > 0 ? hidden_video.videoHeight : 165;
      var width = videoWidth > 640 ? 640 : videoWidth;
      var height = videoHeight * (width / videoWidth);
      // console.log(hidden_video);
      canvas.width = width; //这个设置不能丢，否者会成为canvas默认的300*150的大小
      canvas.height = height; //这个设置不能丢，否者会成为canvas默认的300*150的大小
      let ctx = canvas.getContext("2d"); //创建画布
      // hidden_video.setAttribute('crossOrigin', 'anonymous');

      ctx.drawImage(hidden_video, 0, 0, width, height); //将视频写入canvas

      data = canvas.toDataURL("images/png"); //
      // console.log(data);

      uploadImgBase64({ img: data }).then(res => {
        // console.log(res);
        if (res.data.code == 200) {
          setTimeout(hide, 100);
          let ue = window.UE.getEditor("content");
          ue.focus();
          let datas = `<p></p><p></p><video  src="${url}"  poster="${res.data.data}"
                                controls
                                webkit-playsinline="true"
                                x-webkit-airplay="true"
                                playsinline="true"
                                x5-playsinline="true"
                               >
                                您的浏览器不支持 video 标签。
                                </video><p></p>`;

          ue.execCommand("insertHtml", datas);
        }
      });
    };
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    // 正则验证url地址是否正确
    const myValidateFields = (rule, values, callback) => {
      var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;

      if (values) {
        if (!reg.test(values)) {
          callback("请输入正确的URL");
        }
      }

      callback();
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 }
      }
    };
    let gltjData = this.props.add.gltjData;
    if (!gltjData) {
      gltjData = [];
    }
    //解决Tabs切换时，Footer组件点击保存Acticle组件this无法传递到父Add组件
    this.props.onRef(this);
    const formValues = this.props.form.getFieldsValue();
    return (
      <div className="ArticleMon">
        <Form className="form">
          <FormItem className="title_form_box form_item mon_text1" label="">
            <div className="title">ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ</div>
            {/* <p className="title_show"> */}
              <span className="required" style={{ color: "red" }}>
                *
              </span>
                {getFieldDecorator("information_title", {
                  // rules: [
                  //   {
                  //     required: true,
                  //     message: "ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ᠎ᠶᠢᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ"
                  //   }
                  // ]
                    // initialValue: "测试一回合"
                  })
                  (<Input 
                    placeholder="ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ᠎ᠶᠢᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" 
                    className="artical_title_mon mon_text1 title_input" 
                    onChange={this.getTitleLength} 
                    size="large" 
                  />)

                  // (<div className="title_form_box">
                  //   <div className="title">ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ</div>

                  //   <Input 
                  //     placeholder="ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ᠎ᠶᠢᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" 
                  //     className="title_input" 
                  //     onChange={this.getTitleLength} 
                  //     size="large" 
                  //   />
                  // </div>)
                }
              {/* <span className="rightInput">{this.state.titleLength}/60</span> */}
            {/* </p> */}
          </FormItem>
          <FormItem {...formItemLayout} className="keyword_form_box form_item mon_text1"  label="">
            <div className="keyword ">ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠰᠦᠭ</div>
            {getFieldDecorator("key_word")(
              // <Input
              //   className="keyInput"
              //   onChange={e => {
              //     let data = e.target.value;
              //     if (data.length <= 50) {
              //       this.setState({
              //         keyLength: data.length
              //       });
              //     }
              //   }}
              //   // maxLength={50}
              // />

              // <div className="keyword_form_box mon_text1">
              //   <div className="keyword ">ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠰᠦᠭ</div>
                <Input
                  placeholder="ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠰᠦᠭ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ"
                  className="key_input keyword_input"
                  onChange={e => {
                    let data = e.target.value;
                    if (data.length <= 50) {
                      this.setState({
                        keyLength: data.length
                      });
                    }
                  }}
                />
              // </div>
              )}
            {/* <span className="showKeyLength">{this.state.keyLength}/50</span> */}
          </FormItem>
          <FormItem {...formItemLayout} className="abstract_form_box form_item mon_text1" label="">
            <div className="abstract">ᠲᠣᠪᠴᠢᠯᠠᠯ</div>
            {getFieldDecorator("intro")(
              // <TextArea
              //   placeholder="请输入摘要"
              //   autosize={{ minRows: 2, maxRows: 6 }}
              //   className="introInput"
              //   onChange={e => {
              //     let data = e.target.value;
              //     if (data.length <= 200) {
              //       this.setState({
              //         introLength: data.length
              //       });
              //     }
              //   }}
              //   maxLength={200}
              // />

              // <div className="abstract_form_box mon_text1">
              //   <div className="abstract">ᠲᠣᠪᠴᠢᠯᠠᠯ</div>
                <Input
                  placeholder="ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠲᠣᠪᠴᠢᠯᠠᠯ᠎ᠢᠶᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ"
                  className="abstract_input"
                  onChange={e => {
                    let data = e.target.value;
                    if (data.length <= 200) {
                      this.setState({
                        introLength: data.length
                      });
                    }
                  }}
                  // maxLength={200}
                />
              // </div>
            )}
            {/* <span className="showTextLength">{this.state.introLength}/200</span> */}
          </FormItem>

          <RadioGroup className="form_item radio_group" onChange={this.onChangeRadio} value={this.state.radioValue} style={{ marginBottom: "20px" }}>
            <Radio value={1} className="radio mon_text1 fs_18">ᠨᠠᠢᠷᠠᠭᠤᠯᠬᠤ ᠬᠡᠪ</Radio>
            <Radio value={2} className="radio mon_text1 fs_18">URL ᠬᠡᠪ</Radio>
          </RadioGroup>

          {this.props.add.configJson.mchSwitch ? (
            <Button style={this.state.radioValue === 2 ? { display: "none" } : {}} onClick={this.setUeditor}>
              从内容库选择
            </Button>
          ) : (
            ""
          )}

          <Progress 
            style={this.state.progress === 0 || this.state.progress === 100 ? { display: "none" } : {}} 
            percent={this.state.progress} 
            status="active" 
            showInfo={false}
          />
          
          <div className="form_item ueditor_box" style={this.state.radioValue === 2 ? { display: "none" } : {}}>
            <Ueditor 
              id="content" 
              title={formValues.information_title} 
              configJson={this.props.add.configJson} 
              match={this.props.match} 
            />
          </div>

          <FormItem className="form_item mon_text1" label="">
            {getFieldDecorator("url", {
              rules: [
                {
                  required: false,
                  validator: myValidateFields
                }
              ]
            })(
              <div className="link_form_box mon_text1">
                <div className="link">ᠬᠣᠯᠪᠤᠭᠠᠰᠤ</div>
                <Input className="link_input" placeholder="URL ᠬᠣᠯᠪᠤᠭᠠᠰᠤ᠎ᠪᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" style={this.state.radioValue === 1 ? { display: "none" } : {}} />
              </div>
            )}
          </FormItem>
        </Form>
      </div>
    );
  }
}

const ArticleForm = Form.create()(Article);
export default ArticleForm;
